const execSync = require("child_process").execSync;
const CPU_MAX = Number(process.env.CPU_MAX || 50);
const MEM_MAX = Number(process.env.MEM_MAX || 500);

function monitor() {
  let res = execSync("pm2 list").toString("utf8");
  let arr = res.split("\n");
  let needReload = {};
  arr.forEach(line => {
    let row = line.split("│");
    // 1:name, 2:id, 4:pid, 8:cpu, 9:mem
    if (row.length === 13 && Number(row[4]) > 0) {
      let cpu = Number(row[8].trim().replace("%", ""));
      let mem = 0;
      if (row[9].indexOf("MB") > -1) {
        mem = Number(row[9].replace("MB", "").trim());
      } else if (row[9].indexOf("GB") > -1) {
        mem = Number(row[9].replace("GB", "").trim()) * 1024;
      }
      if (cpu > CPU_MAX || mem > MEM_MAX) {
        needReload[row[1].trim()] = true;
      }
    }
  });

  for (let name in needReload) {
    console.log("gracefulReload", name);
    execSync(`pm2 gracefulReload ${name}`);
  }
}

monitor();
